import { Table, Space, Button, message, Modal, Form, Input } from 'antd'
import React, { useState, useEffect, useImperativeHandle } from 'react'
import { downloadTextFile } from '@/utils'

const { Search } = Input
import {
  FormOutlined,
  DeleteOutlined,
  ApartmentOutlined,
  CloudUploadOutlined,
} from '@ant-design/icons'
import {
  flowInstancePage,
  flowInstanceInsert,
  flowInstanceUpdate,
  flowInstanceDelete,
  exportInstance
} from '@/api/test-case.js'
import { useRef } from 'react'
import { cloneDeep } from 'lodash'
import { useNavigate } from 'react-router-dom'
import TypeTreeSelect from '@/pages/components/type-tree-select/index.jsx'

export const TestCaseList = React.forwardRef((props, ref) => {
  // 1：分支 2 用例
  const busType = 2
  const navigate = useNavigate()
  const { type, typeCode } = props

  const columns = [
    {
      title: '用例名称',
      dataIndex: 'instanceName',
    },
    {
      title: '操作',
      dataIndex: 'key',
      width: '150px',
      render: (key, record, index) => {
        return (
          <Space>
            <Button
              className="icon-btn"
              type="text"
              title='设置'
              icon={<ApartmentOutlined />}
              size="small"
              onClick={() => onView(record)}
            />
             <Button
              className="icon-btn"
              type="text"
              title='导出'
              icon={<CloudUploadOutlined />}
              size="small"
              onClick={() => onExport(record)}
            />
            <Button
             className="icon-btn"
              type="text"
              title='编辑'
              icon={<FormOutlined />}
              size="small"
              onClick={() => onEdit(record)}
            />
            <Button
              className="icon-btn"
              type="text"
              title='删除'
              icon={<DeleteOutlined />}
              size="small"
              onClick={() => onDelete(record)}
            />
          </Space>
        )
      },
    },
  ]

  const inputRef = useRef()
  const [data, setData] = useState([])
  const [query, setQuery] = useState({
    keyWord: '',
    pageNum: 1,
    pageSize: 10
  })

  const [total, setTotal] = useState(0)

  const requestData = () => {
    if (!type || !type.id) {
      setData([])
      setTotal(0)
      return
    }

    flowInstancePage({
      typeId: type.id,
      busType,
      keyWord: query?.keyWord??'',
      pageNum: query?.pageNum??1,
      pageSize: query?.pageSize??10,
    }).then((res) => {
      const { pageInfo } = res.data
      let list = pageInfo.list
      setData(list)
      setTotal(pageInfo.total)
    })
  }

  const [editData, setEditData] = useState(null)

  const onAdd = () => {
    setEditData({
      typeId: type.id,
      busType,
    })
  }
  const onExport=async({id,instanceName})=>{
    const res = await exportInstance({instanceId: id})
    downloadTextFile(JSON.stringify(res),instanceName)
  }

  const onEdit = (record) => {
    setEditData(record)
  }

  const onDelete = (record) => {
    flowInstanceDelete({id: record.id}).then(() => {
      message.success('删除成功')
      onRefresh()
    })
  }

  const onView = (record) => {
    navigate(`/test-case-designer/${record.id}`)
  }

  const onRefresh = () => {
    requestData()
  }

  const onClose = (refresh) => {
    if (refresh) {
      onRefresh()
    }
    setEditData(null)
  }

  useEffect(() => {
    requestData()
  }, [type, query])

  const timer = useRef(null)

  const onSearchChange = (e) => {
    clearTimeout(timer.current)
    
    timer.current = setTimeout(() => {
      setQuery({
       ...query,
        keyWord: e.target.value
      })
    }, 500)
  }
  const onSearch = (keyWord) => {
    setQuery({
      ...query,
      keyWord
    })
  }

  const containerRef = useRef()
  const [scroll, setScroll] = useState(null)
  useEffect(() => {
    if (containerRef.current) {
      let y = containerRef.current.clientHeight - 90
      y = data.length * 48 < y ? false : y
      setScroll(y ? { y } : null)
    }
  }, [containerRef, data])

  const pagination = {
    showTotal() {
      return `共 ${total} 条`
    },
    current: query.pageNum,
    total: total,
    showSizeChanger: true,
    pageSize: query.pageSize,
    onChange(current, pageSize) {
      setQuery({...query, pageNum: current, pageSize })
    },
  }

  useImperativeHandle(
    ref,
    () => ({
      refreshList() {
        setQuery({...query, pageNum: 1, keyWord: '' })
      },
      addFlowStep() {
        onAdd()
      },
    }),
    [type, query]
  )

  return (
    <div className="top-bottom-layout">
      <Search
        ref={inputRef}
        placeholder="请输入关键字查询"
        style={{ width: '20%', marginBottom: 10 }}
        onChange={onSearchChange}
        onSearch={onSearch}
      />
      <div ref={containerRef} className="flex-1">
        <Table
          rowKey="id"
          scroll={scroll}
          columns={columns}
          dataSource={data}
          pagination={pagination}
        ></Table>
        <TestCaseModal
          key={+new Date()}
          typeCode={typeCode}
          initData={editData}
          onClose={onClose}
        />
      </div>
    </div>
  )
})

export const TestCaseModal = (props) => {
  const { typeCode, initData, onClose } = props
  const formRef = useRef()

  const [modalData, setModalData] = useState({
    visible: false,
    confirmLoading: false,
    formData: null,
    rules: {
      instanceName: [{ required: true, message: '请输入测试用例名称' }],
      typeId: [{ required: true, message: '请选择分类' }],
    },
  })

  const [form] = Form.useForm()

  const onEdit = (data) => {
    data = data && data.id ? data : { ...data, instanceName: '' }
    setModalData({
      ...modalData,
      formData: data,
      visible: true,
    })
    form.setFieldsValue({
      instanceName: data.instanceName,
    })
  }

  const onOk = () => {
    formRef.current.validateFields().then((value) => {
      const submitData = cloneDeep(value)
      let menthod = flowInstanceInsert
      if (modalData.formData.id) {
        menthod = flowInstanceUpdate
      }
      setModalData({
        ...modalData,
        confirmLoading: true,
      })
      menthod({ ...modalData.formData, ...submitData }).then(() => {
        onClose(true)
        message.success('保存成功')
        setModalData({
          ...modalData,
          visible: false,
          confirmLoading: false,
        })
      })
    })
  }

  const onCancel = () => {
    setModalData({
      ...modalData,
      visible: false,
    })
    onClose(false)
  }

  useEffect(() => {
    if (initData) {
      onEdit(initData)
    }
  }, [initData])

  return (
    <Modal
      centered
      title={
        modalData.formData && modalData.formData.id
          ? '编辑测试用例'
          : '新增测试用例'
      }
      confirmLoading={modalData.confirmLoading}
      open={modalData.visible}
      onOk={onOk}
      onCancel={onCancel}
    >
      <Form
        ref={formRef}
        form={form}
        layout="vertical"
        initialValues={modalData.formData}
      >
        <Form.Item label="分类" name="typeId" rules={modalData.rules.typeId}>
          <TypeTreeSelect typeCode={typeCode} />
        </Form.Item>
        <Form.Item
          label="测试用例名称"
          name="instanceName"
          rules={modalData.rules.instanceName}
        >
          <Input placeholder="请输入测试用例名称" autoComplete='off'/>
        </Form.Item>
      </Form>
    </Modal>
  )
}

TestCaseList.displayName = 'TestCaseList'

export default TestCaseList
